package com.yxc.mambalibrary.http.okhttp;

import android.os.Looper;
import com.squareup.okhttp.*;
import com.squareup.okhttp.Response;
import com.yxc.mambalibrary.http.*;

import java.io.IOException;
import java.util.HashMap;

/**
 * OkHttpRequest
 * Created by robin on 15/12/4.
 *
 * @author yangxc
 */
public class OkHttpRequest extends AbsBaseRequest {

    public final String TAG = "OkHttpRequest";

    public OkHttpRequest(String tag) {
        super(tag);
    }

    @Override
    public void doRequest(Method method, IRequestParameter parameter, IRequestCallBack callBack) {
        Request.Builder builder = new Request.Builder();
        builder = builder.url(parameter.generateGetURL());
        for (RequestHeader header: parameter.getHeaders()){
            builder.addHeader(header.getKey(), header.getValue());
        }
        Request request = builder.build();
        OkHttpClient client = OkHttpClientHolder.getInstance().getClient();
        Call call = client.newCall(request);

        final HashMap<String, Object> messageObj = new HashMap<>();
        messageObj.put(CallBackHandler.KEY_REQUEST, this);

        final CallBackHandler handler = new CallBackHandler(Looper.getMainLooper(), callBack);
        handler.sendMessage(handler.obtainMessage(CallBackHandler.EVENT_TYPE_START, messageObj));
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                messageObj.put(CallBackHandler.KEY_ERROR, new RequestException());
                handler.sendMessage(handler.obtainMessage(CallBackHandler.EVENT_TYPE_FAILURE, messageObj));
            }

            @Override
            public void onResponse(Response response) throws IOException {
                messageObj.put(CallBackHandler.KEY_RESPONSE, new JsonResponse(response));
                handler.sendMessage(handler.obtainMessage(CallBackHandler.EVENT_TYPE_SUCCESS, messageObj));
            }
        });
    }
}
